﻿#region

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml;

#endregion

namespace MUIExt.MUIExt
{
    public partial class MUIExtUserControl : UserControl
    {
        public MUIExt MUIExt { private get; set; }

        private static Int32 CompareWebParts(WebPart x, WebPart y)
        {
            var stringTable = new[] { x.Title, y.Title };

            Array.Sort(stringTable);

            if (stringTable[0] == stringTable[1]) return 0;

            if (stringTable[0] == x.Title) return -1;

            return 1; //if (stringTable[0] == y.Title) return 1;
        }

        public void Initialize(IEnumerable<CultureInfo> supportedUICultures)
        {
            // Create WebPartManager
            var webPartManager = WebPartManager.GetCurrentWebPartManager(Page);
            if (webPartManager == null) throw new Exception("webPartManager is null");

            // Get current language
            labelCurrentLanguage.Text = "Current Language: " + Thread.CurrentThread.CurrentUICulture.EnglishName + " - " + Thread.CurrentThread.CurrentUICulture.LCID;

            // Get page languages
            labelPageLanguages.Text = "Page languages: ";

            foreach (var cultureInfo in supportedUICultures)
                labelPageLanguages.Text += cultureInfo.EnglishName + " - " + cultureInfo.LCID + ", ";

            labelPageLanguages.Text = labelPageLanguages.Text.TrimEnd(new[] { ',', ' ' });

            // Get current webpart
            labelCurrentWebpart.Text = "Current webpart: " + MUIExt.Title + " - " + MUIExt.ID;

            // Get page webparts
            labelPageWebparts.Text = "Page webparts: ";

            foreach (var webPart in
                webPartManager.WebParts.Cast<WebPart>().Where(webPart => webPart.ID != MUIExt.ID))
                labelPageWebparts.Text += webPart.Title + " - " + webPart.ID + ", ";

            labelPageWebparts.Text = labelPageWebparts.Text.TrimEnd(new[] { ',', ' ' });

            // Load configuration
            var xmlDocument = new XmlDocument();
            xmlDocument.LoadXml(MUIExt.MUIExtConfiguration);

            tableConfiguration.Rows.Clear();

            var tableRowHeader = new TableRow { TableSection = TableRowSection.TableHeader };

            var tableHeaderCell = new TableHeaderCell { Text = "Webparts" };
            tableRowHeader.Cells.Add(tableHeaderCell);

            foreach (var tableHeaderCell2 in
                supportedUICultures.Select(cultureInfo => new TableHeaderCell { Text = cultureInfo.EnglishName }))
                tableRowHeader.Cells.Add(tableHeaderCell2);

            tableConfiguration.Rows.Add(tableRowHeader);

            // Sort webparts
            var listWebParts = webPartManager.WebParts.Cast<WebPart>().ToList();
            listWebParts.Sort(CompareWebParts);

            foreach (var webPart in listWebParts)
            {
                if (webPart.ID == MUIExt.ID) continue;

                var tableRow = new TableRow { TableSection = TableRowSection.TableBody };

                var tableCell = new TableCell { Text = webPart.Title };
                tableCell.Attributes.Add("ID", webPart.ID);
                tableRow.Cells.Add(tableCell);

                foreach (var cultureInfo in supportedUICultures)
                {
                    var tableCell2 = new TableCell { HorizontalAlign = HorizontalAlign.Center };
                    tableCell2.Attributes.Add("Language", cultureInfo.EnglishName);
                    tableCell2.Attributes.Add("LCID", cultureInfo.LCID.ToString());

                    var checkBox = new CheckBox();
                    var booleanShowWebpart = false;

                    var xmlNodeListWebparts = xmlDocument.SelectNodes("Webparts/Webpart");
                    if (xmlNodeListWebparts == null) throw new Exception("xmlNodeListWebparts is null");
                    foreach (XmlNode xmlNodeWebpart in xmlNodeListWebparts)
                    {
                        if (xmlNodeWebpart.Attributes == null) throw new Exception("xmlNodeWebpart.Attributes is null");
                        if (xmlNodeWebpart.Attributes["ID"].Value != webPart.ID) continue;

                        var xmlNodeListLanguages = xmlNodeWebpart.SelectNodes("Languages/Language");
                        if (xmlNodeListLanguages == null) throw new Exception("xmlNodeListLanguages is null");
                        foreach (XmlNode xmlNodeLanguage in xmlNodeListLanguages)
                        {
                            if (xmlNodeLanguage.Attributes == null) throw new Exception("xmlNodeLanguage.Attributes is null");
                            if (xmlNodeLanguage.Attributes["LCID"].Value != cultureInfo.LCID.ToString()) continue;

                            checkBox.Checked = true;
                            booleanShowWebpart = true;
                            break;
                        }
                    }

                    tableCell2.Controls.Add(checkBox);
                    tableRow.Cells.Add(tableCell2);

                    // Apply configuration
                    if (Thread.CurrentThread.CurrentUICulture.LCID == cultureInfo.LCID)
                        webPart.Hidden = !booleanShowWebpart;

                    // Show all webparts if not in BrowseDisplayMode
                    if (webPartManager.DisplayMode != WebPartManager.BrowseDisplayMode)
                        webPart.Hidden = false;
                }

                tableConfiguration.Rows.Add(tableRow);
            }
        }

        protected void ButtonSaveConfigurationClick(object sender, EventArgs e)
        {
            // Save configuration
            var xmlDocument = new XmlDocument();

            XmlNode xmlNodeWebparts = xmlDocument.CreateElement("Webparts");
            xmlDocument.AppendChild(xmlNodeWebparts);

            foreach (TableRow tableRow in tableConfiguration.Rows)
            {
                if (tableRow.TableSection != TableRowSection.TableBody) continue;

                XmlNode xmlNodeWebpart = xmlDocument.CreateElement("Webpart");
                xmlNodeWebparts.AppendChild(xmlNodeWebpart);

                XmlNode xmlNodeLanguages = xmlDocument.CreateElement("Languages");
                xmlNodeWebpart.AppendChild(xmlNodeLanguages);

                foreach (TableCell tableCell in tableRow.Cells)
                {
                    if (tableCell.Text != String.Empty)
                    {
                        var xmlAttributeName = xmlDocument.CreateAttribute("Name");
                        xmlAttributeName.Value = HttpUtility.HtmlEncode(tableCell.Text);
                        if (xmlNodeWebpart.Attributes == null) throw new Exception("xmlNodeWebpart.Attributes is null");
                        xmlNodeWebpart.Attributes.Append(xmlAttributeName);

                        var xmlAttributeID = xmlDocument.CreateAttribute("ID");
                        xmlAttributeID.Value = tableCell.Attributes["ID"];
                        xmlNodeWebpart.Attributes.Append(xmlAttributeID);
                    }
                    else if (((CheckBox)tableCell.Controls[0]).Checked)
                    {
                        XmlNode xmlNodeLanguage = xmlDocument.CreateElement("Language");
                        xmlNodeLanguages.AppendChild(xmlNodeLanguage);

                        var xmlAttributeName = xmlDocument.CreateAttribute("Name");
                        xmlAttributeName.Value = tableCell.Attributes["Language"];
                        if (xmlNodeLanguage.Attributes == null) throw new Exception("xmlNodeLanguage.Attributes is null");
                        xmlNodeLanguage.Attributes.Append(xmlAttributeName);

                        var xmlAttributeID = xmlDocument.CreateAttribute("LCID");
                        xmlAttributeID.Value = tableCell.Attributes["LCID"];
                        xmlNodeLanguage.Attributes.Append(xmlAttributeID);
                    }
                }
            }
            MUIExt.MUIExtConfiguration = xmlDocument.OuterXml;
            MUIExt.SaveProperties();
        }
    }
}